package com.example.weather.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.weather.R;
import com.example.weather.utils.AppUtils;
import com.example.weather.utils.ConstantsUtil;
import com.example.weather.utils.NetWorkUtils;
import com.example.weather.utils.SharePreferenceManager;
import com.thinkpage.lib.api.TPCity;
import com.thinkpage.lib.api.TPLifeSuggestion;
import com.thinkpage.lib.api.TPListeners;
import com.thinkpage.lib.api.TPWeatherDaily;
import com.thinkpage.lib.api.TPWeatherManager;
import com.thinkpage.lib.api.TPWeatherNow;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private String mDefaultCity = "大连";
    private final String apiKey = "exv7a60meq94rybh";
    private final String userId = "U2894ECDB9";
    private Date startDate;
    private TPWeatherManager.TPWeatherReportLanguage mLaungage = TPWeatherManager.TPWeatherReportLanguage.kSimplifiedChinese;
    private TPWeatherManager.TPTemperatureUnit mTemperatureUnit = TPWeatherManager.TPTemperatureUnit.kCelsius;
    private TPWeatherManager weatherManager;

    private TextView mTemperatureTextView;
    private TextView mWindSpeedTextView;
    private TextView mWindDirectionTextView;
    private TextView mUvTextView;
    private ImageView mWeatherImageView;
    private TextView mCityTextView;
    private TextView mNowWeatherTextView;

    private TextView mTomorrowWeatherTextView;
    private TextView mDayAfterTomorrowTextView;
    private TextView mDayTwoAfterTomorrowTextView;
    private ImageView mTomorrowWeatherImageView;
    private ImageView mDayAfterTomorrowWeatherImageView;
    private ImageView mDayTwoAfterTomorrowWeatherImageView;

    private TextView mDressTextView;
    private TextView mDietTextView;

    private String nowWeatherText;
    private String nowWeatherCodeText;
    private ImageView mMenuImageView;

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private int[] screenWidthAndHeight;
    private boolean isShow;
    private PopupWindow popLeft;

    private String mShareContent;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InitView();
        getWeatherData();
    }

    private void InitView(){
        mDefaultCity = SharePreferenceManager.getDefaultCity(getApplicationContext());
        screenWidthAndHeight = AppUtils.getScreenHeightAndWidth(this);
        mTemperatureTextView = (TextView)findViewById(R.id.tv_degree);
        mWindSpeedTextView = (TextView)findViewById(R.id.tv_wind_speed);
        mWindDirectionTextView = (TextView)findViewById(R.id.tv_wind_direction);
        mUvTextView = (TextView)findViewById(R.id.tv_uv_degree);
        mWeatherImageView = (ImageView) findViewById(R.id.iv_weather);
        mCityTextView = (TextView)findViewById(R.id.tv_city);
        mNowWeatherTextView = (TextView)findViewById(R.id.tv_weather);
        mCityTextView.setText(mDefaultCity);

        mTomorrowWeatherTextView = (TextView)findViewById(R.id.tv_tomorrow_high_low);
        mDayAfterTomorrowTextView = (TextView)findViewById(R.id.tv_day_after_tomorrow);
        mDayTwoAfterTomorrowTextView = (TextView)findViewById(R.id.tv_day_two_after_tomorrow);
        mTomorrowWeatherImageView = (ImageView) findViewById(R.id.iv_tomorrow);
        mDayAfterTomorrowWeatherImageView = (ImageView) findViewById(R.id.iv_day_after_tomorrow);
        mDayTwoAfterTomorrowWeatherImageView = (ImageView) findViewById(R.id.iv_day_two_after_tomorrow);

        mDietTextView = (TextView)findViewById(R.id.tv_diet_content);
        mDressTextView = (TextView)findViewById(R.id.tv_dress_content);
        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.sr_refresh_layout);
        mMenuImageView = (ImageView) findViewById(R.id.iv_menu);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        ClickListener clickListener = new ClickListener();
        mMenuImageView.setOnClickListener(clickListener);

        LayoutInflater inflater = LayoutInflater.from(this);
        View layoutLeft = inflater.inflate(R.layout.menu_layout, null,false);
        popLeft = new PopupWindow(layoutLeft, (int)(screenWidthAndHeight[0] * 0.3),
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popLeft.setTouchable(true); // 设置popupwindow可点击
        popLeft.setOutsideTouchable(true);
        ((TextView)layoutLeft.findViewById(R.id.tv_change_city)).setOnClickListener(clickListener);
        ((TextView)layoutLeft.findViewById(R.id.tv_share)).setOnClickListener(clickListener);
        ((TextView)layoutLeft.findViewById(R.id.tv_calender)).setOnClickListener(clickListener);
    }

    private class ClickListener implements View.OnClickListener {
        public void onClick(View v) {
            if (v.getId() == R.id.iv_menu) {
                if(!isShow) {
                    popLeft.showAsDropDown(v, 0, (v.getHeight()) / 6);
                    isShow = true;
                }else{
                    popLeft.dismiss();
                    isShow = false;
                }
            }else if(v.getId() == R.id.tv_change_city){
                popLeft.dismiss();
                isShow = false;
                Intent intent = new Intent(MainActivity.this, ChangeCityActivity.class);
                startActivityForResult(intent, ConstantsUtil.REQUEST_CITY);
            }else if(v.getId() == R.id.tv_share){
                mShareContent = getShareContent();
                Intent intent = new Intent(MainActivity.this, ShareActivity.class).putExtra("content",mShareContent);
                startActivity(intent);
            }else if(v.getId() == R.id.tv_calender){
                popLeft.dismiss();
                isShow = false;
                Intent intent = new Intent(MainActivity.this, CalendarActivity.class);
                startActivity(intent);
            }
        }
    }


    private String getShareContent(){
        String data = "";
        data = data + mDefaultCity +":\n"
                +"天气："+"晴"
                +"气温："+mTemperatureTextView.getText().toString()
                +"风速:"+mWindSpeedTextView.getText().toString()
                +"风向:"+mWindDirectionTextView.getText().toString();
        return data;
    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 根据上面发送过去的请求码来区别
        switch (requestCode) {
            case ConstantsUtil.REQUEST_CITY:
                String newCity = SharePreferenceManager.getDefaultCity(getApplicationContext());
                mDefaultCity = newCity;
                mCityTextView.setText(mDefaultCity);
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        mSwipeRefreshLayout.setRefreshing(true);
                    }
                });
                onRefresh();
                break;
            default:
                break;
        }
    }


    private void getWeatherData(){
        weatherManager = TPWeatherManager.sharedWeatherManager();
        handler = new MyHandler();
        //使用心知天气官网获取的key和用户id初始化WeatherManager
        weatherManager.initWithKeyAndUserId(apiKey,userId);
        startDate = new Date(System.currentTimeMillis());//获取当前时间
        getNowWeather();
        GetThreeDayWeatherMessage();
        String params = "key="+apiKey+"&location="+ mDefaultCity+"&language=zh-Hans";
        NetWorkUtils.sendMessageByGet(ConstantsUtil.Get_Get_Life_Message,params,handler,ConstantsUtil.Get_Life_Message_Id);
    }

    public class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == ConstantsUtil.Get_Life_Message_Id) {
                handleLifeMessage(msg);
            }
        }

        private void handleLifeMessage(Message msg){
            try{
                String obj = msg.obj.toString();
                JSONObject message = new JSONObject(obj);
                JSONArray resultsJSONArray = message.getJSONArray("results");
                JSONObject resultJSONObject;
                JSONObject suggestJSONObject;
                JSONObject dressingJSONObject;
                JSONObject dietJSONObject;
                Map<String,Object> map = new HashMap<>();
                if(resultsJSONArray.length() > 0){
                    resultJSONObject = resultsJSONArray.getJSONObject(0);
                    suggestJSONObject = resultJSONObject.getJSONObject("suggestion");
                    try {
                        dressingJSONObject = suggestJSONObject.getJSONObject("dressing");
                        mDressTextView.setText(dressingJSONObject.getString("details"));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try {
                        dietJSONObject = suggestJSONObject.getJSONObject("beer");
                        mDietTextView.setText(dietJSONObject.getString("details"));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void getNowWeather(){
        try {
            weatherManager.getWeatherNow(new TPCity(mDefaultCity), TPWeatherManager.TPWeatherReportLanguage.kSimplifiedChinese
                    , TPWeatherManager.TPTemperatureUnit.kCelsius, new TPListeners.TPWeatherNowListener() {
                        @Override
                        public void onTPWeatherNowAvailable(TPWeatherNow weatherNow, String errorInfo) {
                            if (weatherNow != null) {
                                mTemperatureTextView.setText(weatherNow.temperature + "c");
                                mWindSpeedTextView.setText(weatherNow.windSpeed + "km/h");
                                mWindDirectionTextView.setText(weatherNow.windDirection + "");
                                nowWeatherText = weatherNow.text;
                                mNowWeatherTextView.setText(nowWeatherText);
                                nowWeatherCodeText = weatherNow.code;
                                int index = Integer.parseInt(nowWeatherCodeText);
                                if (index != 99) {
                                    mWeatherImageView.setImageResource(R.mipmap.p00 + index);
                                } else {
                                    mWeatherImageView.setImageResource(R.mipmap.p00 + 39);
                                }

                            } else {
                                Toast.makeText(MainActivity.this, "获取当天天气异常", Toast.LENGTH_LONG).show();

                            }
                        }
                    });
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private void GetThreeDayWeatherMessage(){
        try {
            final int days = 3;
            weatherManager.getWeatherDailyArray(new TPCity(mDefaultCity), TPWeatherManager.TPWeatherReportLanguage.kSimplifiedChinese
                    , TPWeatherManager.TPTemperatureUnit.kCelsius, startDate, days, new TPListeners.TPWeatherDailyListener() {
                        @Override
                        public void onTPWeatherDailyAvailable(TPWeatherDaily[] tpWeatherDailies, String errorInfo) {
                            if (tpWeatherDailies != null && tpWeatherDailies.length == days) {
                                mTomorrowWeatherTextView.setText(tpWeatherDailies[0].highTemperature + "c/" +
                                        tpWeatherDailies[0].lowTemperature + "c");
                                mDayAfterTomorrowTextView.setText(tpWeatherDailies[1].highTemperature + "c/" +
                                        tpWeatherDailies[0].lowTemperature + "c");
                                mDayTwoAfterTomorrowTextView.setText(tpWeatherDailies[2].highTemperature + "c/" +
                                        tpWeatherDailies[0].lowTemperature + "c");

                                int codeDayOne = Integer.parseInt(tpWeatherDailies[0].codeDay);
                                if (codeDayOne != 99) {
                                    mTomorrowWeatherImageView.setImageResource(R.mipmap.p00 + codeDayOne);
                                } else {
                                    mTomorrowWeatherImageView.setImageResource(R.mipmap.p00 + 39);
                                }

                                int codeDayTwo = Integer.parseInt(tpWeatherDailies[1].codeDay);
                                if (codeDayTwo != 99) {
                                    mDayAfterTomorrowWeatherImageView.setImageResource(R.mipmap.p00 + codeDayTwo);
                                } else {
                                    mDayAfterTomorrowWeatherImageView.setImageResource(R.mipmap.p00 + 39);
                                }

                                int codeDayThree = Integer.parseInt(tpWeatherDailies[2].codeDay);
                                if (codeDayThree != 99) {
                                    mDayTwoAfterTomorrowWeatherImageView.setImageResource(R.mipmap.p00 + codeDayThree);
                                } else {
                                    mDayTwoAfterTomorrowWeatherImageView.setImageResource(R.mipmap.p00 + 39);
                                }

                            } else {
                                Toast.makeText(MainActivity.this, "获取近三天天气异常", Toast.LENGTH_LONG).show();
                            }

                        }
                    });
        }catch (Exception e){
            e.printStackTrace();
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void onRefresh()
    {
        getNowWeather();
        GetThreeDayWeatherMessage();
    }


}
